#     TextLocutor
#     Copyright (C) 2009  Jose Ignacio Naranjo Hernandez (joseignacio.naranjo@gmail.com)

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import urllib
import urllib2
import cookielib
import getpass

class AEConnector(object):
    def __init__(self, app_name='textlocutor',
                 auth_uri='https://www.google.com/accounts/ClientLogin',
                 userid=None,
                 dev_server=False):
        if not userid:
            self.userid = raw_input("Username:")
        else:
            self.userid = userid
 
        # cookie handler
        cookiejar = cookielib.LWPCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
        urllib2.install_opener(opener)
        
        if dev_server:
            params = {'admin': 'True', 'email': self.userid, 'action': 'Login'}
            login_uri = 'http://localhost:8080/_ah/login?%s' % urllib.urlencode(params)
            login_req = urllib2.Request(login_uri)
            self.url_base = 'http://localhost:8080'

        else:
            authreq_data = urllib.urlencode({"Email": self.userid,
                                             "Passwd": getpass.getpass(),
                                             "service": "ah",
                                             "source": app_name,
                                             "accountType": "HOSTED_OR_GOOGLE"})
            auth_req = urllib2.Request(auth_uri, data=authreq_data)
            auth_resp = urllib2.urlopen(auth_req)
            auth_resp_body = auth_resp.read()
            auth_resp_dict = dict(x.split("=")
                                  for x in auth_resp_body.split("\n") if x)
            authtoken = auth_resp_dict["Auth"]

            login_args = {'auth': authtoken}
            login_uri = 'https://%s.appspot.com/_ah/login?%s' % (app_name, 
                                                                 urllib.urlencode(login_args))
            login_req = urllib2.Request(login_uri)
            self.url_base = 'http://%s.appspot.com' % app_name
        try:
            print "Sending authentication to google..."
            login_resp = urllib2.urlopen(login_req)
        except urllib2.HTTPError, e:
            if e.code == 204:
                print "Authentication OK"
            else:
                raise e
        
    def sendRequest(self, uri, params=None):
        if params:
            request = urllib2.Request(uri, params)
        else:
            request = urllib2.Request(uri)
            
        return urllib2.urlopen(request)
        

if __name__ == '__main__': 
    c = AEConnector()
    print c.sendRequest('http://textlocutor.appspot.com/football_scores/').read()
